package com.tln.sys.menu.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javacommon.base.BaseSpringController;

@Controller
@RequestMapping("/sys/uploadify/**")
public class UploadifyController extends BaseSpringController{
	
	private static final Logger logger = LoggerFactory.getLogger(UploadifyController.class);
	
	@RequestMapping
	public String index(HttpServletRequest request,HttpServletResponse response,Model model) {
		logger.info("index.....上传页面.......");
		return "/sys/uploadify/index";
	}
	// 附件:  id  mappingId  realName newName suffixName path uploadDate uploadUser sysName
	//,@RequestParam("uploadFileFileName")String uploadFileFileName
	@RequestMapping(value="/upload",method=RequestMethod.POST)
	public @ResponseBody String upload(HttpServletRequest request,HttpServletResponse response,
			Model model)throws Exception{
		logger.info("upload.....kaishi 上传.......");
		// logger.info("upload.....kaishi changchuan......."+uploadFileFileName);
		Map map = new HashMap();
		String path = UploadifyController.class.getResource("/").getPath()
				.split("WEB-INF")[0]
				+ "upload/annex/"; // 获取站点下的绝对磁盘路径
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		// logger.info("boolean:   "+isMultipart);
		if (!isMultipart)
			return null;

		// logger.info("Multipart request!");

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload();
		upload.setHeaderEncoding("utf-8");
		// Parse the request
		FileItemIterator iter;
		try {
			// debug
			// logger.info("Getting Iterator...");
			iter = upload.getItemIterator(request);
			while (iter.hasNext()) {
				FileItemStream item = iter.next();
				String name = item.getFieldName();
				// logger.info("fujian name : "+name);
				InputStream inputStream = (InputStream) item.openStream();
				if (item.isFormField()) {
					//String fieldValue = Streams.asString(inputStream);
					// debug
					// logger.info("Form field " + name + " with value " +
					// fieldValue + " detected.");
					inputStream.close();
				} else {
					//logger.info("测试:.....................");
					// debug
					// String name = item.getName();
					// logger.info("name:  "+name);
					String fileName = item.getFieldName();
					logger.info("fujian fileName : " + fileName);
					logger.info("File field " + name + " with file name "
							+ item.getName() + " detected.");
					String realFileName = item.getName();
					map.put("name", realFileName);
					logger.info("realFileName  " + realFileName);
					String sortName = "";
					String suffixName = "";// 后缀
					logger.info("" + realFileName.lastIndexOf("."));
					if (realFileName.lastIndexOf(".") >= 0) {
						suffixName = realFileName.substring(realFileName
								.lastIndexOf("."));
						sortName = realFileName.substring(0, realFileName
								.lastIndexOf("."));
					}
					logger.info("suffixName  " + suffixName);
					logger.info("sortName  " + sortName);
					// 进行新的命名
					String newName = FileUpload.getFileName(realFileName);
					File toFile = new File(path, newName);
					logger.info("toFile:   " + toFile);
					// FileUpload.copy(inputStream, bigFile);
					try {
						// InputStream in = null;
						OutputStream out = null;
						try {
							// in = new BufferedInputStream(new
							// FileInputStream(src), BUFFER_SIZE);
							out = new BufferedOutputStream(
									new FileOutputStream(toFile), 16 * 1024);
							byte[] buffer = new byte[16 * 1024];
							while (inputStream.read(buffer) > 0) {
								out.write(buffer);
							}
						} finally {
							if (null != inputStream) {
								inputStream.close();
							}
							if (null != out) {
								out.close();
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					inputStream.close();
					logger.info("File uploaded successfully!");
				}
			}
		} catch (Exception ex) {
			logger.error("" + ex);
			throw new RuntimeException(ex);
		}
		
		
		//resposne 接收数据
		renderJson(response, map);
		  
		return null;
	      //return "redirect:/sys/uploadify";
	      //return "/sys/uploadify/upload";
	}

}
